package mi.payment.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
 * Created by xurong on 2017/9/30.
 */

public class Base64Utils {

    /**
     * 将base64编码字符串转换为图片
     *
     * @param base64Str
     * @param imgPath
     * @return
     */
    public static boolean generateImgByBase64Str(String base64Str, String imgPath) {
        OutputStream out = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(base64Str);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out = new FileOutputStream(imgPath);
            out.write(b);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 把图片文件转换为base64编码字符串
     *
     * @param imgFile
     * @return
     */
    public static String imgFile2Base64Str(File imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            if (data != null) {
                // 加密
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
